<template>
    <el-card style="height: 80px;">
        <el-form :inline="true" class="form">
            <el-form-item label="用户名:">
                <el-input placeholder="请输入用户名" v-model="keyword" @keyup.enter="search"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :disabled="keyword ? false : true" @click="search">搜索</el-button>
                <el-button type="primary" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card style="margin: 10px 0px;">
        <el-button type="primary" @click="addUser">添加用户</el-button>
        <el-button type="danger" @click="deleteSelectUser"
            :disabled="selectIdArr.length ? false : true">批量删除</el-button>
        <el-table border style="margin: 10px 0;" :data="userArr" @selection-change="selectChange">
            <el-table-column align="center" type="selection"></el-table-column>
            <el-table-column align="center" label="#" type="index"></el-table-column>
            <el-table-column align="center" label="ID" prop="id"></el-table-column>
            <el-table-column align="center" label="用户名字" prop="username" show-overflow-tooltip></el-table-column>
            <el-table-column align="center" label="用户名称" prop="name" show-overflow-tooltip></el-table-column>
            <el-table-column align="center" label="用户角色" prop="roleName" show-overflow-tooltip></el-table-column>
            <el-table-column align="center" label="创建时间" prop="createTime" show-overflow-tooltip></el-table-column>
            <el-table-column align="center" label="更新时间" prop="updateTime" show-overflow-tooltip></el-table-column>
            <el-table-column align="center" label="操作" width="300px">
                <template #="{ row }">
                    <el-button type="primary" icon="User" size="small" @click="setRole(row)">分配权限</el-button>
                    <el-button type="primary" icon="Plus" size="small" @click="updateUser(row)">编辑</el-button>
                    <el-popconfirm :title="`你确定要删除${row.username}?`" width="260px" @confirm="deleteUser(row.id)">
                        <template #reference>
                            <el-button type="primary" size="small" icon="Delete">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>

            </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[3, 5, 7, 9]"
            :background="true" layout="prev, pager, next, jumper,->,sizes,total" :total="total"
            @current-change="getHasUserInfo" @size-change="handler" />
    </el-card>
    <!-- 抽屉效果：用于添加或更新用户 -->
    <el-drawer v-model="drawer">
        <template #header>
            <h4 style="text-align: center;font-size: 40px;font-weight: bold;">{{ userParams.id ? '更新用户' : '添加用户' }}</h4>
        </template>
        <template #default>
            <el-form :model="userParams" ref="formRef" :rules="rules">
                <el-form-item label="用户姓名" prop="username">
                    <el-input placeholder="请输入用户名" v-model="userParams.username"></el-input>
                </el-form-item>
                <el-form-item label="用户昵称" prop="name">
                    <el-input placeholder="请输入用户昵称" v-model="userParams.name"></el-input>
                </el-form-item>
                <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
                    <el-input placeholder="请输入用户密码" v-model="userParams.password"></el-input>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="cancle">取消</el-button>
                <el-button type="primary" @click="save">确定</el-button>
            </div>
        </template>
    </el-drawer>
    <!-- 分配角色抽屉:用于分配用户角色 -->
    <el-drawer v-model="drawer1">
        <template #header>
            <h4 style="text-align: center;font-size: 40px;font-weight: bold;">分配角色(职位)</h4>
        </template>
        <template #default>
            <el-form>
                <el-form-item label="用户姓名">
                    <el-input :disabled="true" v-model="userParams.username"></el-input>
                </el-form-item>
                <el-form-item label="职位列表">
                    <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">
                        全选
                    </el-checkbox>
                    <el-checkbox-group v-model="userRole" @change="handleCheckedCitiesChange">
                        <el-checkbox v-for="(role, index) in allRole" :key="index" :label="role">
                            {{ role.roleName }}
                        </el-checkbox>
                    </el-checkbox-group>

                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawer1 = false">取消</el-button>
                <el-button type="primary" @click="confirmClick">确定</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script setup lang="ts">
import useLayOutSettingStore from "@/store/modules/setting"
import { ref, onMounted, reactive, nextTick } from "vue"
import { reqRemoveUser, reqSelectUser, reqUserInfo, reqAddOrUpdateUser, reqAllRole, reqSetUserRole } from "@/api/acl/user"
import type { SetRoleData, UserResponseData, Records, User, AllRoleResponseData, AllRole } from '@/api/acl/user/type';
import { ElMessage } from "element-plus";
// 初始化settingStore
let settingStore = useLayOutSettingStore()
let pageNo = ref<number>(1)
let pageSize = ref<number>(5)
// 定义初始总页数
let total = ref<number>(0)
// 初始接收用户数据
let userArr = ref<Records>([])
// 控制抽屉的显隐
let drawer = ref<boolean>(false)
// 控制分配角色抽屉的显隐
let drawer1 = ref<boolean>(false)
// 定义结收用户信息的对象
let userParams = reactive<User>({
    username: '',
    name: '',
    password: ''
})
// 获取form实例对象
let formRef = ref<any>()
// 初始化全部职位列表
let allRole = ref<AllRole>([])
// 初始化现有职位列表
let userRole = ref<AllRole>([])
// 初始化批量删除用户的数组
let selectIdArr = ref<User[]>([])
// 初始化搜索关键字
let keyword = ref<string>('')
// 组件挂在完毕，发送请求，获取数据
onMounted(() => {
    getHasUserInfo()
})

// 将请求封装为方法
const getHasUserInfo = async (pager = 1) => {
    pageNo.value = pager
    let result: UserResponseData = await reqUserInfo(pageNo.value, pageSize.value, keyword.value)
    if (result.code === 200) {
        total.value = result.data.total
        userArr.value = result.data.records
    }
}

// 分页器下拉触发的事件
const handler = () => {
    getHasUserInfo()
}

// 点击添加用户的回调
const addUser = () => {
    // 清除抽屉的数据
    Object.assign(userParams, {
        id: 0,
        username: '',
        name: '',
        password: ''
    })
    // 清理表单校验的规则
    nextTick(() => {
        formRef.value.clearValidate('username');
        formRef.value.clearValidate('name');
        formRef.value.clearValidate('password');
    })
    drawer.value = true
}

// 点击编辑用户按钮的回调
const updateUser = (row: User) => {
    // 清除抽屉的数据
    Object.assign(userParams, row)
    // 清理表单校验的规则
    nextTick(() => {
        formRef.value.clearValidate('username');
        formRef.value.clearValidate('name');
    })
    drawer.value = true
}

// 点击确定按钮的回调
const save = async () => {
    // 表单校验未通过，不发送请求
    await formRef.value.validate()
    // 关闭抽屉
    drawer.value = false
    let result = await reqAddOrUpdateUser(userParams)
    if (result.code === 200) {
        ElMessage({
            type: 'success',
            message: userParams.id ? '修改成功' : '添加成功'
        })
        //获取最新的全部账号的信息
        // getHasUserInfo(userParams.id ? pageNo.value : 1);
        //浏览器自动刷新一次
        window.location.reload();
    } else {
        ElMessage({
            type: 'error',
            message: userParams.id ? '修改失败' : '添加失败'
        })
    }
}
// 点击取消按钮的回调
const cancle = () => {
    drawer.value = false
}
// 自定义表单校验的方法
const validatorUsername = (_rule: any, value: any, callback: any) => {
    if (value.trim().length >= 6) {
        callback()
    } else {
        callback(new Error('用户名长度不能小于6位'))
    }
}
const validatorName = (_rule: any, value: any, callback: any) => {
    if (value.trim().length >= 6) {
        callback()
    } else {
        callback(new Error('用户昵称不能小于6位'))
    }
}
const validatorPassword = (_rule: any, value: any, callback: any) => {
    if (value.trim().length >= 8) {
        callback()
    } else {
        callback(new Error('用户密码不能小于8位'))
    }
}

// 自定义表单校验的对象
const rules = {
    username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
    name: [{ required: true, trigger: 'blur', validator: validatorName }],
    password: [{ required: true, trigger: 'blur', validator: validatorPassword }],

}
// 点击分配角色按钮的回调
const setRole = async (row: User) => {

    // 存储数据
    Object.assign(userParams, row)
    // 获取所有职位及现有职位
    let result: AllRoleResponseData = await reqAllRole((userParams.id as number))
    console.log(result);
    if (result.code === 200) {
        // 存储数据
        allRole.value = result.data.allRolesList
        userRole.value = result.data.assignRoles
    }
    drawer1.value = true
}
//收集顶部复选框全选数据
const checkAll = ref<boolean>(false);
//控制顶部全选复选框不确定的样式
const isIndeterminate = ref<boolean>(true);
//顶部的全部复选框的change事件
const handleCheckAllChange = (val: boolean) => {
    //val:true(全选)|false(没有全选)
    userRole.value = val ? allRole.value : [];
    //不确定的样式(确定样式)
    isIndeterminate.value = false
}
//顶部全部的复选框的change事件
const handleCheckedCitiesChange = (value: string[]) => {
    //顶部复选框的勾选数据
    //代表:勾选上的项目个数与全部的职位个数相等，顶部的复选框勾选上
    checkAll.value = value.length === allRole.value.length;
    //不确定的样式
    isIndeterminate.value = value.length !== allRole.value.length
}

// 分配角色确定按钮的回调
const confirmClick = async () => {
    // 收集需要的数据
    let data: SetRoleData = {
        userId: userParams.id as number,
        roleIdList: userRole.value.map(item => {
            return item.id as number
        })
    }
    // 发送请求
    let reault: any = await reqSetUserRole(data)
    if (reault.code === 200) {
        ElMessage({
            message: '分配角色成功',
            type: 'success'
        })
        // 关闭抽屉
        drawer1.value = false
        // 重新获取用户列表数据 留在当前页
        getHasUserInfo(pageNo.value)
    }
}

// 点击用户删除按钮的回调
const deleteUser = async (userId: number) => {
    let result: any = await reqRemoveUser(userId)
    if (result.code == 200) {
        ElMessage({ type: 'success', message: '删除成功' });
        getHasUserInfo(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1);
    }
}
//table复选框勾选的时候会触发的事件
const selectChange = (value: any) => {
    selectIdArr.value = value;
}

// 点击批量删除按钮的回调
const deleteSelectUser = async () => {
    // 整理收集的数据
    let idList: any = selectIdArr.value.map(item => {
        return item.id
    })
    let result: any = await reqSelectUser(idList)
    if (result.code == 200) {
        ElMessage({ type: 'success', message: '删除成功' });
        getHasUserInfo(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1);
    }
}

// 点击搜索用户按钮的回调
const search = () => {
    getHasUserInfo()
    // 清空关键字
    keyword.value = ''
}
// 点击重置按钮的回调
const reset = () => {
    settingStore.refsh = !settingStore.refsh
}

</script>
<style lang="scss" scoped>
.form {
    display: flex;
    justify-content: space-between;
    align-items: center
}
</style>